<template>
    <div class="game-logic">
        <div class="level-info" v-if="isGameStarted">
            <div class="level">第 {{ currentLevel }} 关</div>
            <div class="zombies-left">剩余僵尸: {{ zombiesLeft }}</div>
        </div>
        <div
            v-for="zombie in zombies"
            :key="zombie.id"
            class="zombie"
            :style="getZombieStyle(zombie)"
        >
            <img :src="zombie.image" alt="僵尸" />
            <div class="health-bar">
                <div
                    class="health-fill"
                    :style="{
                        width: `${(zombie.health / zombie.maxHealth) * 100}%`,
                    }"
                ></div>
            </div>
        </div>

        <!-- 爆炸效果 -->
        <div
            v-for="explosion in explosions"
            :key="explosion.id"
            class="explosion"
            :style="getExplosionStyle(explosion)"
        ></div>

        <!-- 冰冻效果 -->
        <div
            v-for="freeze in freezeEffects"
            :key="freeze.id"
            class="freeze-effect"
            :style="getFreezeStyle(freeze)"
        ></div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";

const zombies = ref([]);
const explosions = ref([]);
const freezeEffects = ref([]);
let zombieInterval;
let gameLoop;
const isGameStarted = ref(false);
const currentLevel = ref(1);
const zombiesLeft = ref(0);

// 僵尸类型
const zombieTypes = {
    normal: {
        name: "普通僵尸",
        health: 100,
        speed: 1,
        damage: 20,
        image: "/zombies/zombie.svg",
    },
    coneHead: {
        name: "路障僵尸",
        health: 200,
        speed: 0.8,
        damage: 20,
        image: "/zombies/coneheadzombie.svg",
        unlockedAt: 2,
    },
    bucketHead: {
        name: "铁桶僵尸",
        health: 300,
        speed: 0.7,
        damage: 20,
        image: "/zombies/bucketheadzombie.svg",
        unlockedAt: 3,
    },
    poleVaulting: {
        name: "撑杆僵尸",
        health: 150,
        speed: 1.5,
        damage: 20,
        image: "/zombies/polevaultingzombie.svg",
        canJump: true,
        unlockedAt: 4,
    },
};

// 关卡配置
const levelConfig = {
    1: {
        zombieCount: 5,
        zombieTypes: ["normal"],
        spawnInterval: 10000,
    },
    2: {
        zombieCount: 8,
        zombieTypes: ["normal", "coneHead"],
        spawnInterval: 9000,
    },
    3: {
        zombieCount: 10,
        zombieTypes: ["normal", "coneHead", "bucketHead"],
        spawnInterval: 8000,
    },
    4: {
        zombieCount: 12,
        zombieTypes: ["normal", "coneHead", "bucketHead", "poleVaulting"],
        spawnInterval: 7000,
    },
    5: {
        zombieCount: 15,
        zombieTypes: ["normal", "coneHead", "bucketHead", "poleVaulting"],
        spawnInterval: 6000,
    },
    6: {
        zombieCount: 18,
        zombieTypes: ["normal", "coneHead", "bucketHead", "poleVaulting"],
        spawnInterval: 5500,
        multipleRows: true, // 多行同时出现僵尸
    },
    7: {
        zombieCount: 20,
        zombieTypes: ["coneHead", "bucketHead", "poleVaulting"],
        spawnInterval: 5000,
        multipleRows: true,
    },
    8: {
        zombieCount: 25,
        zombieTypes: ["coneHead", "bucketHead", "poleVaulting"],
        spawnInterval: 4500,
        multipleRows: true,
        zombieSpeed: 1.2, // 僵尸速度提升
    },
    9: {
        zombieCount: 30,
        zombieTypes: ["bucketHead", "poleVaulting"],
        spawnInterval: 4000,
        multipleRows: true,
        zombieSpeed: 1.3,
    },
    10: {
        zombieCount: 40,
        zombieTypes: ["bucketHead", "poleVaulting"],
        spawnInterval: 3500,
        multipleRows: true,
        zombieSpeed: 1.5,
        bossLevel: true, // 最终关卡
    },
};

const createZombie = () => {
    if (!isGameStarted.value || zombiesLeft.value <= 0) return;

    const config = levelConfig[currentLevel.value];

    // 确定生成僵尸的行数
    let rows = [Math.floor(Math.random() * 5)]; // 默认随机一行

    // 如果是多行生成模式，随机选择1-3行
    if (config.multipleRows) {
        const rowCount = Math.floor(Math.random() * 3) + 1; // 1到3行
        rows = [];
        for (let i = 0; i < rowCount; i++) {
            let row;
            do {
                row = Math.floor(Math.random() * 5);
            } while (rows.includes(row)); // 确保不重复
            rows.push(row);
        }
    }

    // 为每一行生成僵尸
    rows.forEach((row) => {
        // 随机选择僵尸类型
        const availableTypes = config.zombieTypes;
        const randomType =
            availableTypes[Math.floor(Math.random() * availableTypes.length)];
        const zombieType = zombieTypes[randomType];

        // 应用关卡速度修饰符
        let speed = zombieType.speed;
        if (config.zombieSpeed) {
            speed *= config.zombieSpeed;
        }

        zombies.value.push({
            id: Date.now() + Math.random(), // 确保ID唯一
            row,
            x: 800,
            type: randomType,
            name: zombieType.name,
            health: zombieType.health,
            maxHealth: zombieType.health,
            speed: speed,
            damage: zombieType.damage,
            image: zombieType.image,
            attackInterval: 1000,
            lastAttackTime: 0,
            canJump: zombieType.canJump || false,
            hasJumped: false,
            isFrozen: false,
            frozenUntil: 0,
        });
        zombiesLeft.value--;
    });
};

const moveZombies = () => {
    if (!isGameStarted.value) return;

    const now = Date.now();
    zombies.value.forEach((zombie) => {
        // 如果僵尸被冰冻，检查是否解冻
        if (zombie.isFrozen && now > zombie.frozenUntil) {
            zombie.isFrozen = false;
            zombie.speed = zombieTypes[zombie.type].speed;
        }

        // 移动僵尸
        if (!zombie.isFrozen) {
            zombie.x -= zombie.speed;
        } else {
            zombie.x -= zombie.speed * 0.5; // 冰冻时移动速度减半
        }
    });

    // 移除已经走出屏幕的僵尸
    zombies.value = zombies.value.filter((zombie) => zombie.x > -50);
};

const getZombieStyle = (zombie) => {
    let style = {
        top: `${zombie.row * 20}%`,
        left: `${zombie.x}px`,
    };

    // 如果僵尸被冰冻，添加蓝色滤镜
    if (zombie.isFrozen) {
        style.filter = "hue-rotate(180deg) brightness(1.2)";
    }

    return style;
};

const getExplosionStyle = (explosion) => {
    return {
        top: `${explosion.row * 20}%`,
        left: `${explosion.col * 11.11}%`,
    };
};

const getFreezeStyle = (freeze) => {
    return {
        top: `${freeze.row * 20}%`,
        left: `${freeze.x}px`,
    };
};

const takeDamage = (zombieId, damage, freezeDuration = 0) => {
    const zombie = zombies.value.find((z) => z.id === zombieId);
    if (zombie) {
        zombie.health -= damage;

        // 如果有冰冻效果
        if (freezeDuration > 0) {
            zombie.isFrozen = true;
            zombie.frozenUntil = Date.now() + freezeDuration;
        }

        if (zombie.health <= 0) {
            zombies.value = zombies.value.filter((z) => z.id !== zombieId);
            return true;
        }
    }
    return false;
};

// 创建爆炸效果
const createExplosion = (row, col) => {
    const explosion = {
        id: Date.now(),
        row,
        col,
    };

    explosions.value.push(explosion);

    // 对范围内的僵尸造成伤害
    const damage = 300; // 爆炸伤害
    const killedZombies = [];

    zombies.value.forEach((zombie) => {
        // 检查僵尸是否在爆炸范围内（同一行且距离合适）
        const zombieCol = Math.floor(zombie.x / 60);
        if (zombie.row === row && Math.abs(zombieCol - col) <= 1) {
            if (takeDamage(zombie.id, damage)) {
                killedZombies.push(zombie.id);
            }
        }
    });

    // 3秒后移除爆炸效果
    setTimeout(() => {
        explosions.value = explosions.value.filter(
            (e) => e.id !== explosion.id
        );
    }, 1000);

    return killedZombies.length;
};

// 创建冰冻效果
const createFreezeEffect = (row, targetZombieId) => {
    const zombie = zombies.value.find((z) => z.id === targetZombieId);
    if (!zombie) return;

    const freeze = {
        id: Date.now(),
        row,
        x: zombie.x,
    };

    freezeEffects.value.push(freeze);

    // 1秒后移除冰冻效果
    setTimeout(() => {
        freezeEffects.value = freezeEffects.value.filter(
            (f) => f.id !== freeze.id
        );
    }, 1000);
};

const startGame = () => {
    isGameStarted.value = true;
    currentLevel.value = 1;
    zombies.value = [];
    explosions.value = [];
    freezeEffects.value = [];
    zombiesLeft.value = levelConfig[currentLevel.value].zombieCount;
    // 根据关卡配置生成僵尸
    zombieInterval = setInterval(
        createZombie,
        levelConfig[currentLevel.value].spawnInterval
    );
    // 游戏主循环
    gameLoop = setInterval(moveZombies, 50);
};

const stopGame = () => {
    isGameStarted.value = false;
    clearInterval(zombieInterval);
    clearInterval(gameLoop);
};

const nextLevel = () => {
    if (currentLevel.value < Object.keys(levelConfig).length) {
        currentLevel.value++;
        zombiesLeft.value = levelConfig[currentLevel.value].zombieCount;
        clearInterval(zombieInterval);
        zombieInterval = setInterval(
            createZombie,
            levelConfig[currentLevel.value].spawnInterval
        );
    } else {
        // 通关
        emit("gameWin");
    }
};

onUnmounted(() => {
    stopGame();
});

defineExpose({
    zombies,
    takeDamage,
    createExplosion,
    createFreezeEffect,
    startGame,
    stopGame,
    isGameStarted,
    currentLevel,
    zombiesLeft,
    nextLevel,
});
</script>

<style scoped>
.game-logic {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
}

.level-info {
    position: absolute;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 10px 20px;
    border-radius: 5px;
    display: flex;
    gap: 20px;
    font-size: 18px;
    z-index: 100;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

.zombie {
    position: absolute;
    width: 60px;
    height: 80px;
    transition: left 0.05s linear;
}

.zombie img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.health-bar {
    position: absolute;
    top: -10px;
    left: 0;
    width: 100%;
    height: 5px;
    background: #ff0000;
    border-radius: 2px;
}

.health-fill {
    height: 100%;
    background: #00ff00;
    border-radius: 2px;
    transition: width 0.3s ease;
}

.explosion {
    position: absolute;
    width: 120px;
    height: 120px;
    background: radial-gradient(
        circle,
        rgba(255, 0, 0, 0.8) 0%,
        rgba(255, 165, 0, 0.6) 50%,
        rgba(255, 255, 0, 0.4) 100%
    );
    border-radius: 50%;
    transform: translate(-30px, -30px);
    animation: explode 1s forwards;
    z-index: 100;
}

@keyframes explode {
    0% {
        transform: translate(-30px, -30px) scale(0.1);
        opacity: 0;
    }
    50% {
        transform: translate(-30px, -30px) scale(1);
        opacity: 1;
    }
    100% {
        transform: translate(-30px, -30px) scale(1.5);
        opacity: 0;
    }
}

.freeze-effect {
    position: absolute;
    width: 80px;
    height: 80px;
    background: radial-gradient(
        circle,
        rgba(173, 216, 230, 0.8) 0%,
        rgba(135, 206, 235, 0.6) 50%,
        rgba(0, 191, 255, 0.4) 100%
    );
    border-radius: 50%;
    transform: translate(-10px, -10px);
    animation: freeze 1s forwards;
    z-index: 90;
}

@keyframes freeze {
    0% {
        transform: translate(-10px, -10px) scale(0.1);
        opacity: 0;
    }
    50% {
        transform: translate(-10px, -10px) scale(1);
        opacity: 0.8;
    }
    100% {
        transform: translate(-10px, -10px) scale(1.2);
        opacity: 0;
    }
}
</style>
